# -*- coding: utf-8 -*-
from Site import *
import re

class SiteTaobao(Site):

    def __init__(self, cc):
        Site.__init__(self, cc)
        self.website = '淘宝'
        self.websiteLink = 'http://s.taobao.com/search?q=%s'
        self.pageLink = 'http://s.taobao.com/search?q=%s&tab=all&s=%s'

    def getAll(self, keyword):
        page = self.searchHomePage(keyword, type = 'js')

        page_count = self.getPageCount(page)
        count = 0

        self.log('homepage', page)
        self.log('info', '#page = %d' % page_count)

        for page_no in range(page_count):
            if self.cc.isQuitted():
                break

            if page_no > 0:
                page = self.searchPage(keyword, page_no * 44, type = 'js')
                if page == None:
                    break

            products = self.getProducts(page)

            self.log('info', '#products = %d' % len(products))
            if len(products) == 0:
                self.logDB('products=0', '', unicode(page))
                break

            product_list = []
            for product in products:
                if self.cc.isQuitted():
                    break

                pi = self.getProduct(product)
                if pi == None:
                    continue

                self.log('info', 'add product %d - %s' % (count, pi.id))
                product_list.append(pi)

                count += 1
                if count >= self.cc.MaxProducts:
                    break

            if self.cc.isQuitted():
                break

            for pi in product_list:
                self.logProduct(pi)
                pi.save(self.cc.UserId, self.cc.TaskId, keyword, self.website)

            if count >= self.cc.MaxProducts:
                break

    def getProducts(self, page):
        try:
            products = page.find_all('div', {'nid': re.compile('\d+')})
            if len(products) == 0:
                products = page.find_all('div', {'class': 'item '})
                if len(products) == 0:
                    products = page.find_all('div', {'class': 'item'})

            return products
        except:
            pass

        return []

    def getPageCount(self, page):
        try:
            tag = page.find('div', {'class': 'page-top'})
            if tag:
                tag1 = tag.find('span')
                if tag1:
                    s = tag1.get_text().strip()
                    mo = re.search('/(?P<count>\d+)', s)
                    if mo:
                        return int(mo.group('count'))

            tag = page.find('span', {'class': 'crumbs-items'})
            if tag:
                tag1 = tag.find('span', {'class': 'H'})
                if tag1:
                    return int(tag1.get_text().strip())
        except:
            pass

        return 1

    def getProduct(self, product):
        pi = ProductInfo()

        pi.id = self.getId(product)
        if pi.id == '':
            return None

        pi.link = self.getLink(pi.id)
        pi.name = self.getName(product)
        pi.price = self.getPrice(product)

        if not pi.isValid():
           self.logProduct(pi)
           self.logDB('getProduct failed', '', unicode(product))
           return None 

        pi.factory.id = self.getFactoryId(product)
        pi.factory.name = self.getFactoryName(product)

        product_page = self.openPage(pi.link, type = 'js', referer = pi.link)
        if product_page:
            pi.sellCount = self.getSellCount(product_page)
            pi.leftCount = self.getLeftCount(product_page, pi.link)

        factory_page = self.openPage('http://s.taobao.com/search?bid=%s&sid=%s&app=api&m=get_shop_card' % (pi.id, pi.factory.id), type = 'raw_json', referer = pi.link)
        if factory_page:
            if 'url' in factory_page:
                pi.factory.link = factory_page['url']
            pi.factory.rank = self.getFactoryRank(factory_page)
            
        return pi

    def getId(self, page):
        try:
            tag = page.find('a')
            if tag:
                href = tag['href']
                if href:
                    if 'tmall' in href:
                        return ''

                    mo = re.search('id=(?P<id>\d+)', href)
                    if mo:
                        return mo.group('id')
        except Exception, e:
            self.logException(e)

        return ''

    def getLink(self, id):
        return 'http://item.taobao.com/item.htm?id=' + id

    def getName(self, page):
        try:
            tag = page.find('div', {'class':'title'})
            if tag:
                tag1 = tag.find('a')
                if tag1:
                    if 'title' in tag1.attrs:
                        return tag1['title']

                    return tag1.get_text().strip()
        except:
            pass

        return ''
        
    def getPrice(self, page):
        try:
            tag = page.find('span', {'class': 'price-num'})
            if tag:
                return float(tag.get_text().strip())

            tag = page.find('div', {'class': 'price'})
            if tag:
                tag1 = tag.find('strong')
                if tag1:
                    return float(tag1.get_text().strip())
        except Exception, e:
            self.logException(e)

        return ''

    def getFactoryId(self, page):
        try:
            tag = page.find('a', {'class': 'shop-name'})
            if tag:
                href = tag['href']
                if href:
                    mo = re.search('user_number_id=(?P<id>\d+)', href)
                    if mo:
                        return mo.group('id')

            tag = page.find('a', {'class': 'shopname'})
            if tag:
                href = tag['href']
                if href:
                    mo = re.search('user_number_id=(?P<id>\d+)', href)
                    if mo:
                        return mo.group('id')
        except:
            pass

        return ''
        
    def getFactoryLink(self, id):
        return 'http://store.taobao.com/iew_shop.htm?user_number_id=' + id
        
    def getFactoryName(self, page):
        try:
            tag = page.find('a', {'class': 'shop-name'})
            if tag:
                return tag.get_text().strip()

            tag = page.find('a', {'class': 'shopname'})
            if tag:
                return tag.get_text().strip()
        except:
            pass

        return ''
        
    def getSellCount(self, page):
        try:
            s = str(page)
            pos1 = s.find('"apiItemInfo":"')
            if pos1 >= 0:
                s1 = s[pos1 + len('"apiItemInfo":"'):]
                pos2 = s1.find('",')
                link = s1[:pos2]
                if link:
                    s = self.openPage(link, type = 'raw')
                    pos1 = s.find('confirmGoods:')
                    if pos1 >= 0:
                        s1 = s[pos1 + len('confirmGoods:'):]
                        pos2 = s1.find(',')
                        count = s1[:pos2].strip()
                        return int(count.strip())
        except Exception, e:
            self.logException(e)

        return ''
        
    def getLeftCount(self, page, referer):
        try:
            s = str(page)
            pos1 = s.find('"wholeSibUrl":"')
            if pos1 >= 0:
                s1 = s[pos1 + len('"wholeSibUrl":"'):]
                pos2 = s1.find('",')
                link = s1[:pos2]
                if link:
                    s = str(self.openPage(link, type = 'js', referer = referer))
                    pos1 = s.find('"stock":')
                    if pos1 >= 0:
                        s1 = s[pos1 + len('"stock":'):]
                        pos2 = s1.find('"')
                        if pos2 >= 0:
                            s2 = s1[pos2 + 1:]
                            pos3 = s2.find('"')
                            if pos3 >= 0:
                                s3 = s2[:pos3]
                                return int(s3.strip())
        except:
            pass

        return ''

    def getFactoryRank(self, factory_page):
        if not factory_page:
            return ''

        try:
            rank_count = 0
            rank = ''
            for item in factory_page['levelClasses']:
                rank_count += 1
                if '-zuan' in item['levelClass']:
                    rank = u'钻'
                elif '-guan' in item['levelClass']:
                    rank = u'蓝冠'
                elif '-xin' in item['levelClass']:
                    rank = u'心'
                elif '-jinguan' in item['levelClass']:
                    rank = u'金冠'

            if rank == '':
                return ''

            return u'%d%s' % (rank_count, rank)
        except Exception, e:
            self.logException(e)

        return ''
        
